package cn.wildfirechat.app.controller;

import cn.wildfirechat.app.update.AppVersion;
import cn.wildfirechat.app.update.dto.ResultVo;
import cn.wildfirechat.app.update.dto.VersionCheckRequest;
import cn.wildfirechat.app.update.dto.VersionCheckResponse;
import cn.wildfirechat.app.update.AppVersionService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/version")
@CrossOrigin
public class AppVersionController {
    
    @Autowired
    private AppVersionService appVersionService;
    
    /**
     * 检查版本更新（Android端调用）
     */
    @PostMapping("/check")
    public ResultVo<VersionCheckResponse> checkVersion(@RequestBody VersionCheckRequest request) {
        VersionCheckResponse response = appVersionService.checkVersion(request);
        return ResultVo.success(response);
    }
    
    /**
     * 获取最新版本信息
     */
    @GetMapping("/latest")
    public ResultVo<AppVersion> getLatestVersion(@RequestParam String platform) {
        AppVersion latestVersion = appVersionService.getLatestVersion(platform);
        return ResultVo.success(latestVersion);
    }
    
    /**
     * 获取版本列表（分页）
     */
    @GetMapping("/list")
    public ResultVo<IPage<AppVersion>> getVersionList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String platform) {
        Page<AppVersion> page = new Page<>(current, size);
        IPage<AppVersion> result = appVersionService.getVersionList(page, platform);
        return ResultVo.success(result);
    }
    
    /**
     * 添加版本
     */
    @PostMapping
    public ResultVo<String> addVersion(@RequestBody AppVersion appVersion) {
        boolean success = appVersionService.addVersion(appVersion);
        return success ? ResultVo.success("添加成功") : ResultVo.error("添加失败");
    }
    
    /**
     * 更新版本
     */
    @PutMapping("/{id}")
    public ResultVo<String> updateVersion(@PathVariable Long id, @RequestBody AppVersion appVersion) {
        appVersion.setId(id);
        boolean success = appVersionService.updateVersion(appVersion);
        return success ? ResultVo.success("更新成功") : ResultVo.error("更新失败");
    }
    
    /**
     * 删除版本
     */
    @DeleteMapping("/{id}")
    public ResultVo<String> deleteVersion(@PathVariable Long id) {
        boolean success = appVersionService.deleteVersion(id);
        return success ? ResultVo.success("删除成功") : ResultVo.error("删除失败");
    }
    
    /**
     * 启用/禁用版本
     */
    @PutMapping("/{id}/toggle")
    public ResultVo<String> toggleVersion(@PathVariable Long id) {
        boolean success = appVersionService.toggleVersion(id);
        return success ? ResultVo.success("操作成功") : ResultVo.error("操作失败");
    }
}